<?php

namespace App\Service\OpenShop\FeishuMini;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\SiteLocationEnum;
use App\Enums\OpenShop\MissionTemplateEnum;
use App\Library\Rms\RmsShopApi;
use App\Models\College\CollegeTrainingOrderModel;
use App\Models\College\CollegeTrainingPlanModel;
use App\Models\Guanyuan\GuanyuanSyncShopListModel;
use App\Models\OpenShop\Common\OpenShopProvinceTargetModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopLocationModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationRegionMappingModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopProcessDetailModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSpaceDesignSoftLogisticsModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserBaseInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationExamineLogModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Remote\Rms\RmsShopRemote;
use App\Service\Common\CommonService;
use App\Service\Fee\FeishuApply\FeeAnnualOrderService;
use App\Service\OpenShop\Feishu\MainProcessService;
use App\Service\OpenShop\Feishu\NoticeService;
use App\Service\OpenShop\Feishu\OrganizationManageService;
use App\Service\OpenShop\Feishu\PermissionService;
use App\Service\OpenShop\Feishu\SelectionService;
use App\Service\OpenShop\Feishu\SiteMissionService;
use App\Service\OpenShop\Feishu\StartBusinessService;
use App\Service\OpenShop\Merchant\OrderProgressService;
use App\Service\OpenShop\OrderService;
use App\Service\OpenShop\Statistical\SignOrderStatisticalService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Kuafu\express\KuafuExpress;

class ShopService
{
    const TIME_TYPE_MONTH = 1; // 月
    const TIME_TYPE_YEAR  = 2; // 年

    private array $orderPermission;

    public function __construct(array $orderPermission = [])
    {
        if ($orderPermission) {
            $this->orderPermission = $orderPermission;
        } else {
            $this->orderPermission = [
                'isAll'  => false,
                'rawSql' => '',
            ];
        }
    }

    public function overview(): array
    {
        $totalCount = 0;

        $lists = [
            [
                'text'            => '全部',
                'stepStatusLists' => [],
                'count'           => &$totalCount,
            ],
            [
                'text'            => '选址中',
                'stepStatusLists' => MissionTemplateEnum::SITE_STATUS,
                'count'           => 0,
            ],
            [
                'text'            => '筹备中',
                'stepStatusLists' => MissionTemplateEnum::PREPARE_STATUS,
                'count'           => 0,
            ],
            [
                'text'            => '已营业',
                'stepStatusLists' => [MissionTemplateEnum::STEP_STATUS_999],
                'count'           => MainProcessService::countByStepStatus($this->orderPermission,
                    MissionTemplateEnum::STEP_STATUS_999),
            ],
            [
                'text'            => '开业报告待提交',
                'stepStatusLists' => [MissionTemplateEnum::STEP_STATUS_18],
                'count'           => 0,
            ],
            [
                'text'            => '装修保证金待退',
                'stepStatusLists' => [MissionTemplateEnum::STEP_STATUS_100],
                'count'           => 0,
            ],
        ];

        $diffLists = OrderService::getDifferentV2($this->orderPermission);

        foreach ($diffLists as $mainLists) {
            foreach ($mainLists['value'] as $step) {
                $count      = $step['count'];
                $stepStatus = (int)$step['stepStatusStr'];

                foreach ($lists as &$v) {

                    // 全部
                    if ($v['stepStatusLists'] == []) {
                        continue;
                    }

                    // 对应的阶段
                    if (in_array($stepStatus, $v['stepStatusLists'])) {
                        $v['count'] += $count;
                        break;
                    }
                }
            }
        }

        // 全部加和
        foreach ($lists as $vv) {
            if ($vv['stepStatusLists'] != [MissionTemplateEnum::STEP_STATUS_100]) {
                $totalCount += $vv['count'];
            }
        }

        return $lists;

    }

    public function miniShopLists(
        string $search,
        int $cityCode,
        string $signStartDate,
        string $signEndDate,
        string $locationStartDate,
        string $locationEndDate,
        string $openingStartDate,
        string $openingEndDate,
        int $pageSize,
        int $pageNum,
        array $stepStatusLists
    ): array {

        $signStartTime     = $signStartDate ? strtotime($signStartDate) : 0;
        $signEndTime       = $signEndDate ? strtotime($signEndDate) + 86399 : 0;
        $locationStartTime = $locationStartDate ? strtotime($locationStartDate) : 0;
        $locationEndTime   = $locationEndDate ? strtotime($locationEndDate) + 86399 : 0;
        $openingStartTime  = $openingStartDate ? strtotime($openingStartDate) : 0;
        $openingEndTime    = $openingEndDate ? strtotime($openingEndDate) + 86399 : 0;

        $shopCode = 0;
        $username = '';
        if ($search) {
            if (preg_match("/^\d+$/", $search)) {

                // 纯数字，即店铺号
                $shopCode = (int)$search;
            } else {

                // 老板姓名
                $username = (string)$search;
            }
        }

        $paginates = OpenShopSignOrderModel
            ::query()
            ->where('status', '>', SignOrderEnum::ORDER_STATUS_NO)
            ->with([
                'shopLocationRel' => function ($query) {
                    $query->select('orderNo', 'openTime');
                },
                'progressRel',
                'identityCardRel',
                'addressRel',
                'contractRel'     => function ($q) {
                    $q->with(['templateRel'])
                      ->select();
                },
            ])
            ->when(!$this->orderPermission['isAll'], function ($query) {
                $query->whereRaw("open_shop_sign_order." . $this->orderPermission['rawSql']);
            })
            ->when($shopCode, function ($query) use ($shopCode) {
                $query->where('shopCode', $shopCode);
            })
            ->when($username, function ($query) use ($username) {
                $query->join('open_shop_main_process as process', 'process.id', '=',
                    'open_shop_sign_order.mainProcessId')
                      ->join('open_shop_user_identity_card as identity', 'identity.orderNo', '=', 'process.orderNo')
                      ->where('identity.name', 'like', "%{$username}%")
                      ->addSelect('process.id', 'identity.name');
            })
            ->when($cityCode, function ($query) use ($cityCode) {
                $query->join('open_shop_address as address', 'address.orderNo', '=', 'open_shop_sign_order.orderNo')
                      ->where('address.cityCode', $cityCode);
            })
            ->when($signStartTime && $signEndTime,
                function ($query) use ($signStartTime, $signEndTime) {
                    $query->whereBetween('signTime', [$signStartTime, $signEndTime]);
                })
            ->when($locationStartTime && $locationEndTime,
                function ($query) use ($locationStartTime, $locationEndTime) {
                    $query->join('open_shop_location as location', 'location.orderNo', '=',
                        'open_shop_sign_order.orderNo')
                          ->whereBetween('location.confirmTime', [$locationStartTime, $locationEndTime]);
                })
            ->when($openingStartTime && $openingEndTime,
                function ($query) use ($openingStartTime, $openingEndTime) {
                    $query->join('open_shop_location as location2', 'location2.orderNo', '=',
                        'open_shop_sign_order.orderNo')
                          ->whereBetween('location2.openTime', [$openingStartTime, $openingEndTime]);
                })
            ->when($stepStatusLists, function ($query) use ($stepStatusLists) {
                if ($stepStatusLists == [MissionTemplateEnum::STEP_STATUS_100]) {
                    $query->whereIn('open_shop_sign_order.orderNo',
                        OpenShopUserContractModel::getRefundDecorationDepositOrderCountOrderNos($this->orderPermission['rawSql']));
                } else {
                    $query->join('open_shop_main_process as process2', 'process2.id', '=',
                        'open_shop_sign_order.mainProcessId')
                          ->whereIn('process2.nowStepStatus', $stepStatusLists);
                }
            })
            ->select('open_shop_sign_order.*')
            ->orderByDesc('open_shop_sign_order.id')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);

        $shopCodes = collect($paginates->items())->pluck('shopCode')->toArray();
        $shopInfos = collect(RmsShopRemote::getShopFieldsByCodes($shopCodes,
                ['shopCode', 'name', 'formalUseAt'])['shopList'] ?? [])->keyBy('shopCode');

        $lists = collect($paginates->items())->map(function ($item) use ($shopInfos) {

            // 开业时间，默认取rms，为0时，取预计开业时间
            $openTime = $shopInfos[$item->shopCode]['formalUseAt'] ?? 0;
            if (!$openTime) {
                $openTime = (int)optional($item->shopLocationRel)->openTime;
                $isOpen   = false;
            } else {
                $isOpen = true;
            }

            $nowStepStatus = (int)optional($item->progressRel)->nowStepStatus;

            // tags
            // 是否 迁址
            $tagLocationStatus = false;
            if (!empty($item->mainProcessRel->childLocationOrder)) {
                $tagLocationStatus = (bool)$item->mainProcessRel->childLocationOrder;
            }
            // 是否合同变更
            $changeContract = true;
            // 是否接解除协议
            $removeContract = true;
            // 是否异常
            $exceptionMsg = optional($item->contractRel)->exceptionMsg;
            $isAbnormal   = !empty($exceptionMsg);
            // 合
            $isConfirm = $item->step < SignOrderEnum::STEP_2;
            // 多
            $shopCount = optional($item->contractRel)->shopCount ?? 1;
            $isDuoShop = $shopCount > 1;
            // 离
            $isQuit = false; // 未知

            $tags = OrderService::getOrderTags(
                1,
                $tagLocationStatus,
                $item->contractStatus == OpenShopSignOrderModel::CONTRACT_STATUS_CHANGE,
                $item->dissolveStatus > OpenShopSignOrderModel::DISSOLVE_STATUS_NORMAL && $item->status != SignOrderEnum::ORDER_STATUS_NO,
                $isAbnormal,
                $isConfirm,
                $isDuoShop,
                $isQuit,
                false,
                SiteLocationFeiShuMiniService::getKeyPointByOrderNo($item->orderNo) //重
            );
            return [
                'orderNo'           => $item->orderNo,
                'shopCode'          => 'KF' . $item->kfShopCode,
                'userName'          => $userName = (string)optional($item->identityCardRel)->name,
                'shopName'          => $item->shopCode ? ($shopInfos[$item->shopCode]['name'] ?? '') : ($userName . '的店'),
                'shopAddressPrefix' => (string)optional($item->addressRel)->addressPrefix ?: '-',
                'signTime'          => $item->signTime ? date('Y-m-d', $item->signTime) : '-',
                'openTime'          => $openTime ? date('Y-m-d', $openTime) : '-',
                'isOpen'            => $isOpen,
                'statusText'        => MissionTemplateEnum::STEP_STATUS_TEXT[$nowStepStatus] ?? '-',
                'tags'              => $tags
            ];
        });

        return [
            'count'    => $count = $paginates->total(),
            'pageMax'  => ceil($count / $pageSize) ?: 1,
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'list'     => $lists,
        ];
    }

    /**
     * 能看首页的权限
     * @return bool
     */
    public function indexAccess(): bool
    {
        $dataPermission = PermissionService::dataPermission(PermissionService::URI_SIGN_ORDER);

        // 判断身份
        // 1.省总看省区
        // 2.全部订单权限看全部
        // 3.其他不给看
        if ($dataPermission == PermissionService::PERMISSION_DENY || $dataPermission == PermissionService::PERMISSION_PERSON) {
            return false;
        }

        return true;
    }

    // 夸父开店小程序首页
    public function index(int $dataPermission, int $userId, int $timeType): array
    {
        // 判断身份
        // 1.省总、城市经理看省区
        // 2.全部订单权限看全部
        // 3.其他不给看
        if ($dataPermission == PermissionService::PERMISSION_DENY || $dataPermission == PermissionService::PERMISSION_PERSON) {
            return [];
        }

        // 获取对应的provinceCode lists
        if ($dataPermission == PermissionService::PERMISSION_PROVINCE) {
            $areaList = OrganizationManageService::getAreaListByUserId($userId);
            if ($areaList['isAll']) {
                $provinceCodes = OpenShopOrganizationRegionMappingModel::getTotalProvinceCode();
            } else {
                $provinceCodes = $areaList['list'];
            }
        } elseif ($dataPermission == PermissionService::PERMISSION_CITY) {
            $provinceCodes = [];
            OpenShopOrganizationManageUserModel::query()
                ->where('userId', $userId)
                ->where('type', OpenShopOrganizationManageUserModel::TYPE_CITY_MANAGER)
                ->get()
                ->map(function (OpenShopOrganizationManageUserModel $openShopOrganizationManageUserModel) use (&$provinceCodes) {
                    $provinceCodes = array_merge($provinceCodes, array_column($openShopOrganizationManageUserModel->addressCodesArr, 'provinceCode'));
                });
            $provinceCodes = array_values(array_unique($provinceCodes));
        } elseif ($dataPermission == PermissionService::PERMISSION_ALL) {
            $provinceCodes = OpenShopOrganizationRegionMappingModel::getTotalProvinceCode();
        } else {
            return [];
        }

        if ($timeType == self::TIME_TYPE_YEAR) {

            // 年
            $openStartTime        = strtotime(date('Y', time()) . '-01-01 00:00:00');
            $yearMonth            = date('Y');
            $dataSourceOpeningKey = 'stillOpenShopNum'; // 观远在营
            $dataSourceNewKey     = 'newOpenShopNumYear'; // 观远年度新增

//            $signOrderService = new SignOrderStatisticalService();
//            $signOrderService->setTimeInterval($openStartTime, time());
//            $dataSourceLists = $signOrderService->getGyAnnualShopData();

            $dataSourceLists = [];
        } else {

            // 月
            $openStartTime        = strtotime(date('Y-m', time()) . '-01 00:00:00');
            $yearMonth            = date('Ym');
            $dataSourceOpeningKey = 'stillOpenShopNumMonth';
            $dataSourceNewKey     = 'newOpenShopNumMonthGyWeek';

//            $signOrderService = new SignOrderStatisticalService();
//            $dataSourceLists  = $signOrderService->getGYStatusWeek();

            $dataSourceLists = [];
        }
//
//        // rms批量查询每个省的在营门店, 本月新开
//        $rmsLists = collect((new RmsShopApi())
//                ->overviewByProvinceCodes($provinceCodes, $openStartTime, time())['data']['lists'] ?? [])
//            ->keyBy('provinceCode');


        // 每个省的目标
        $targetLists = OpenShopProvinceTargetModel::query()
                                                  ->whereIn('provinceCode', $provinceCodes)
                                                  ->where('yearMonth', $yearMonth)
                                                  ->get()
                                                  ->keyBy('provinceCode');

        // 批量查询每个省，任务数量
        $missionLists = $this->indexMissionLists($provinceCodes, $openStartTime, time());

        $lists = collect($provinceCodes)->map(function ($provinceCode) use (
            $dataSourceLists,
            $targetLists,
            $missionLists,
            $dataSourceOpeningKey,
            $dataSourceNewKey
        ) {
            return [
                'province' => [
                    'code' => $provinceCode,
                    'name' => OpenShopOrganizationRegionMappingModel::getProvinceName($provinceCode),
                ],
                'opening'  => [
                    'finish' => $dataSourceLists[$provinceCode]['templateValue'][$dataSourceOpeningKey] ?? 0,
                    'target' => $targetLists[$provinceCode]['stockNum'] ?? 0,
                ],
                'new'      => [
                    'finish' => $dataSourceLists[$provinceCode]['templateValue'][$dataSourceNewKey] ?? 0,
                    'target' => $targetLists[$provinceCode]['openNum'] ?? 0,
                ],
                'mission'  => $missionLists->map(function ($item) use ($provinceCode) {
                    $item['num'] = $item['numLists'][$provinceCode]['ct'] ?? 0;
                    unset($item['numLists']);

                    return $item;
                }),
            ];
        });

        // 全部合计
        $total = [
            'province' => [
                'code' => 0,
                'name' => '全部'
            ],
            'opening'  => [
                'finish' => 0,
                'target' => 0,
            ],
            'new'      => [
                'finish' => 0,
                'target' => 0,
            ],
            'mission'  => [],
        ];
        $lists->each(function ($item) use (&$total) {
            $total['opening']['finish'] += $item['opening']['finish'];
            $total['opening']['target'] += $item['opening']['target'];
            $total['new']['finish']     += $item['new']['finish'];
            $total['new']['target']     += $item['new']['target'];

            foreach ($item['mission'] as $k => $mission) {
                $total['mission'][$k]['text'] = $mission['text'];

                isset($total['mission'][$k]['num']) ?: $total['mission'][$k]['num'] = 0;
                $total['mission'][$k]['num'] += $mission['num'];
            }
        });

        $lists = $lists->prepend($total)->toArray();

        return $lists;
    }

    private function indexMissionLists(array $provinceCodes, int $startTime, int $endTime): Collection
    {
        $baseQuery = OpenShopSignOrderModel::query()
                                           ->join('open_shop_user_base_info as info', 'info.orderNo', '=',
                                               'open_shop_sign_order.orderNo')
                                           ->whereIn('info.chooseShopProvinceCode', $provinceCodes)
                                           ->where('open_shop_sign_order.status', '>', SignOrderEnum::ORDER_STATUS_NO)
                                           ->groupBy('info.chooseShopProvinceCode')
                                           ->selectRaw('info.chooseShopProvinceCode as provinceCode, count(*) as ct');

        return collect([
            [
                'text'     => '新签约', // 累计
                'numLists' => (clone $baseQuery)
                    ->whereBetween('signTime', [$startTime, $endTime])
                    ->get()
                    ->keyBy('provinceCode')
                    ->toArray(),
            ],
            [
                'text'     => '选址中',
                'numLists' => (clone $baseQuery)
                    ->join('open_shop_main_process as main', 'open_shop_sign_order.mainProcessId',
                        '=', 'main.id')
                    ->whereIn('main.nowStepStatus', MissionTemplateEnum::SITE_STATUS)
                    ->get()
                    ->keyBy('provinceCode')
                    ->toArray(),
            ],
            [
                'text'     => '已落址', // 累计
                'numLists' => (clone $baseQuery)
                    ->join('open_shop_site_locations as location', 'location.orderNo', 'open_shop_sign_order.orderNo')
                    ->whereBetween('merchantConfirmTime', [$startTime, $endTime])
                    ->get()
                    ->keyBy('provinceCode')
                    ->toArray(),

            ],
            [
                'text'     => '筹备中',
                'numLists' => (clone $baseQuery)
                    ->join('open_shop_main_process as main', 'open_shop_sign_order.mainProcessId', '=', 'main.id')
                    ->whereIn('main.nowStepStatus', MissionTemplateEnum::PREPARE_STATUS)
                    ->get()
                    ->keyBy('provinceCode')
                    ->toArray(),
            ],
        ]);
    }


    /**
     * @throws Exception
     * @throws GuzzleException
     */
    public static function detail($orderNo)
    {
        //根据订单号获得用户基本信息
        $orderModel = OpenShopSignOrderModel::query()
                                            ->where('orderNo', $orderNo)
                                            ->with(['identityCardRel', 'baseInfoRel', 'contractRel'])
                                            ->first();
        //获得选址表单
        $siteLocation = OpenShopSiteLocationModel::query()
                                                 ->where('orderNo', $orderNo)
            ->whereIn('source',
                [
                    OpenShopSiteLocationModel::SOURCE_OPEN_SHOP,
                    OpenShopSiteLocationModel::SOURCE_HOUSING
                ])
                                                 ->with([
                                                     'examineLogsRel' => function ($query) {
                                                         $query->where('source',
                                                             OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
                                                               ->where('status',
                                                                   OpenShopSiteLocationExamineLogModel::STATUS_OK);
                                                     }
                                                 ])
                                                 ->first();
        //获得门店ID
        $shopId = OpenShopMainProcessModel::query()->where('orderNo', $orderNo)->value('shopId');
        if (!$orderModel) {
            return [];
        }
        $shopInfo = $orderModel->shopCode ? (RmsShopRemote::getShopFieldsByCodes([$orderModel->shopCode])['shopList'][0]['name'] ?? '-') : '-';
        if ($siteLocation != null) {
            if ($siteLocation->examineLogsRel->toArray()) {
                $shopCreatedDate = $siteLocation->examineLogsRel[0]->createdAt->toDateString();
            }
            $shopInformation = [
                'code'             => $orderModel->shopCode,
                'name'             => $shopInfo,
                'type'             => \App\Service\Rms\ShopService::SHOP_TYPE_MAPPING[$shopInfo['shopList'][0]['type'] ?? 0] ?? '-',
                'area'             => $siteLocation->cityArea,
                'address'          => $siteLocation->address,
                'rentType'         => SiteLocationEnum::RENT_TYPE_TEXT[$siteLocation->rentType] ?? '-',
                'fixedRent'        => round($siteLocation->fixedRent / 12, 2),
                'remind'           => $siteLocation->remind,
                'rentPaymentCycle' => SiteLocationEnum::RENT_PAYMENT_MONTH[$siteLocation->rentPaymentCycle] ?? '-',
                'deposit'          => $siteLocation->deposit,
                'leaseTerm'        => $siteLocation->leaseTerm,
                'rentFreePeriod'   => $siteLocation->rentFreePeriod,
                'caseRegisterType' => SiteLocationEnum::CASE_REGISTER_TEXT[$siteLocation->caseRegisterType] ?? '',
                'createdDate'      => $shopCreatedDate ?? '-',
            ];
        } else {
            $shopInformation = [
                'code'             => 'KF-' . $orderModel->shopCode,
                'name'             => (optional($orderModel->identityCardRel)->name ?: '-') . '的店',
                'type'             => '-',
                'area'             => '-',
                'address'          => '-',
                'rentType'         => '-',
                'fixedRent'        => 0,
                'remind'           => 0,
                'rentPaymentCycle' => 0,
                'deposit'          => 0,
                'leaseTerm'        => 0,
                'rentFreePeriod'   => 0,
                'caseRegisterType' => '-',
                'createdDate'      => '-',
            ];
        }
        $information = [
            'name'              => '-',
            'area'              => '-',
            'address'           => '-',
            'username'          => '-',
            'phone'             => '-',
            'supplier'          => '-',
            'position'          => '-',
            'brand'             => '-',
            'orderWeek'         => '-',
            'receiveWeek'       => '-',
            'distributionCycle' => 0,
            'minOrderAmount'    => 0,
            'startOrderTime'    => '-',
            'latestOrderTime'   => '-',
            'firstOrderAmount'  => 0,
            'createdDate'       => '-',
        ];
        //订货
        $urlOrm      = config('orm.domain') . \App\Service\OpenShop\Merchant\OrderService::ORM_GET_CODE_INFO;
        $bodyOrm     = ['brandId' => 1, 'shopId' => $shopId ?: -1];
        $headerOrm   = ['internal-key' => config('orm.internalKey'), 'internal-token' => config('orm.internalValue')];
        $responseOrm = getOrmMessageCommon("GET", $urlOrm, $bodyOrm, $headerOrm, 'query');
        if ($responseOrm['code'] == 0) {
            try {
                $information = [
                    'name'              => $responseOrm['data']['name'],
                    'area'              => $responseOrm['data']['province'] . '-' . $responseOrm['data']['city'] . '-' . $responseOrm['data']['county'],
                    'address'           => $responseOrm['data']['address'],
                    'username'          => $responseOrm['data']['contact_man'],
                    'phone'             => $responseOrm['data']['phone'],
                    'supplier'          => $responseOrm['data']['supplier_text'],
                    'position'          => $responseOrm['data']['position_text'],
                    'brand'             => $responseOrm['data']['brand_text'],
                    'orderWeek'         => $responseOrm['data']['order_week_text'],
                    'receiveWeek'       => $responseOrm['data']['receive_week_text'],
                    'distributionCycle' => $responseOrm['data']['distribution_cycle'],
                    'minOrderAmount'    => $responseOrm['data']['min_order_amount'],
                    'startOrderTime'    => $responseOrm['data']['start_order_time'],
                    'latestOrderTime'   => $responseOrm['data']['latest_order_time'],
                    'firstOrderAmount'  => $responseOrm['data']['first_order_amount'],
                    'createdDate'       => $responseOrm['data']['create_time'],
                ];
            } catch (\Exception $exception) {
                Log::info('获取物流信息失败', ['shopId' => $shopId]);
            }
        }
        $paymentOrigin = \App\Service\OpenShop\Merchant\OrderService::orderPayHistory($shopId ?: 0);

        $orderDetail = OpenShopSignOrderModel::orderDetail(
            $orderNo,
            true,
            true,
            true,
            true,
            false,
            true,
            true,
            true,
            0,
            true
        );

        $shopLocation = $orderDetail->getIterator()->current()->shopLocationRel ?: null;
        if ($shopLocation) {
            ($shopLocation->openTime = formatDate($shopLocation->openTime));
            $shopLocation->shopLocationReportUrl = privateFilePath($shopLocation->shopLocationReportUrl);
            $imgList                             = SelectionService::getImgList($orderNo);
            $shopLocation['imgMapping']          = $imgList;
            // 获取门店名称

            $shopName                 = SiteMissionService::getRmsShopNameByCode([
                    $orderDetail->getIterator()->current()->shopCode
                ])['shopList'][0]['name'] ?? "还没有店名";
            $shopLocation['shopName'] = $shopName;
        }

        return array_merge($paymentOrigin, [
            'baseInfo'      => [
                'orderNo'    => $orderNo,
                'contractNo' => 'KF-' . $orderModel->shopCode,
                'name'       => optional($orderModel->identityCardRel)->name ?: '-',
                'mobile'     => optional($orderModel->baseInfoRel)->mobile ?: '-',
                'wechat'     => optional($orderModel->baseInfoRel)->weChatNumber ?: '-',
                'area'       => optional($orderModel->baseInfoRel)->addressPrefix ?: '-',
                'address'    => optional($orderModel->baseInfoRel)->address ?: '-',
                'postalCode' => optional($orderModel->baseInfoRel)->postCode ?: '-',
            ],
            'shopInfo'      => $shopInformation,
            'information'   => $information,
            'startBusiness' => StartBusinessService::detail($orderNo)["detail"],
            'shopLocation'  => $shopLocation,
        ]);
    }

    //获得门店软装信息
    public static function softOutfit($orderNo)
    {
        return OpenShopSpaceDesignSoftLogisticsModel::query()
            ->where('orderNo', $orderNo)
            ->get()
            ->map(function ($item) {
                return [
                    'name'             => $item->productName,
                    'type'             => $item->type,
                    'typeText'         => OpenShopSpaceDesignSoftLogisticsModel::CN_TYPE[$item->type] ?? '-',
                    'logisticsName'    => $item->logisticsName,
                    'logisticsNumber'  => $item->logisticsNumber,
                    'expressName'      => $item->expressName,
                    'expressNumber'    => $item->expressNumber,
                    'expressNumberUrl' => $item->expressNumber ? KuafuExpress::webUrl($item->expressNumber, $item->expressEnName) : '',
                    'receiverName'     => $item->receiverName,
                    'receiverNumber'   => $item->receiverNumber,
                    'receiverAddress'  => $item->receiverAddress,
                ];
            })->toArray();
    }

    /**
     * 城市门店
     *
     * @param object $params
     * @return mixed|void
     * @throws GuzzleException
     */
    public static function cityShop(object $params)
    {
        try{
            return RmsShopRemote::cityShop($params->cityCode, $params->shopName);
        }catch (Exception $exception){
            handleException($exception);
        }
    }

    /**
     * 根据shopId获得培训校区
     * @param int $shopId
     * @return array|string[]
     */
    public static function getTrainSchool(int $shopId): array
    {
        $planId = (int)CollegeTrainingOrderModel::query()
            ->where('studentShopId', $shopId)
            ->where('status', '!=', CollegeTrainingOrderModel::STATUS_CLOSE)
            ->orderByDesc("createdAt")
            ->value('planId');

        if (!$planId) {
            return ['schoolName' => ''];
        }

        $campus = CollegeTrainingPlanModel::query()
            ->where('id', $planId)
            ->value('campus');

        return ['schoolName' => CollegeTrainingPlanModel::TRAINING_PLANS_CAMPUS_MAPPING[$campus]];
    }

    /**
     * 根据shopId判断是属于叁代店
     * @param int $shopId
     * @return array
     */
    public static function getShopPatternByShopId(int $shopId): array
    {
        $orderNo = OpenShopMainProcessModel::query()
            ->where('shopId', $shopId)
            ->orderByDesc('id')
            ->value('orderNo');

        if (!strlen($orderNo)) {
            return ['shopPattern' => 0];
        }

        $shopPattern = OpenShopSiteLocationModel::query()
            ->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)
            ->where('orderNo', $orderNo)
            ->value('shopPattern');

        return [
            'shopPattern' => $shopPattern
        ];
    }

    /**
     * rms门店属性修改同步到选址表单中
     * @param int $shopId
     * @param array $data
     * @return array
     */
    public static function updateShopAttribute(int $shopId, array $data): array
    {
        $orderNo = OpenShopMainProcessModel::query()
            ->where('shopId', $shopId)
            ->orderByDesc('id')
            ->value('orderNo');

        if (!strlen($orderNo)) {
            return [];
        }

        $siteLocation = OpenShopSiteLocationModel::query()
            ->whereIn('source', [OpenShopSiteLocationModel::SOURCE_OPEN_SHOP, OpenShopSiteLocationModel::SOURCE_HOUSING])
            ->where('orderNo', $orderNo)
            ->first();

        if ($siteLocation) {
            $update = [];
            if (isset($data['shopType']) && $data['shopType'] != $siteLocation->shopType) {
                $update['shopType'] = $data['shopType'];
            }
            if (isset($data['siteSelection']) && $data['siteSelection'] != $siteLocation->siteSelection) {
                $update['siteSelection'] = $data['siteSelection'];
            }
            if (isset($data['sellingCategory']) && $data['sellingCategory'] != $siteLocation->sellingCategory) {
                $update['sellingCategory'] = $data['sellingCategory'];
            }
            if (isset($data['menuLevel']) && $data['menuLevel'] != $siteLocation->menuLevel) {
                $update['menuLevel'] = $data['menuLevel'];
            }
            if (isset($data['posLine']) && $data['posLine'] != $siteLocation->posLine) {
                $update['posLine'] = $data['posLine'];
            }
            if (isset($data['engineeringExhibitionArea']) && $data['engineeringExhibitionArea'] != $siteLocation->doorHeadWidth) {
                $update['doorHeadWidth'] = $data['engineeringExhibitionArea'];
            }
            if (isset($data['engineeringArea']) && $data['engineeringArea'] != $siteLocation->area) {
                $update['area'] = $data['engineeringArea'];
            }
            if (isset($data['engineeringDepth']) && $data['engineeringDepth'] != $siteLocation->depth) {
                $update['depth'] = $data['engineeringDepth'];
            }
            if (isset($data['engineeringElectricity']) && $data['engineeringElectricity'] != $siteLocation->electricityConsumption) {
                $update['electricityConsumption'] = $data['engineeringElectricity'];
            }
            if (isset($data['posTypeEnum']) && $data['posTypeEnum'] != $siteLocation->caseRegisterType) {
                $update['caseRegisterType'] = $data['posTypeEnum'];
            }
            if ($update) {
                OpenShopSiteLocationModel::query()->where('id', $siteLocation->id)->update($update);
            }
        }

        $location = OpenShopLocationModel::query()->where('orderNo', $orderNo)->first();
        if ($location && isset($data['cashType'])) {
            $cashType = $data['posTypeEnum'] ?? 0;
            if ($cashType != $location->cashType) {
                $location->cashType = $cashType;
                $location->save();
            }
        }
        return [];
    }


    /**
     * 根据门店ID查询门店属性
     * @param array $shopIds
     * @param string $type
     * @return array
     */
    public static function getShopAttributeByShopIds(array $shopIds, string $type): array
    {
        if ($type == 'guanyuan') {// 取观远门店状态
            return GuanyuanSyncShopListModel::query()
                ->join('kf_shops', 'kf_shops.shopCode', '=', 'guanyuan_sync_shop_list.code')
                ->whereIn('kf_shops.id', $shopIds)
                ->select(['guanyuan_sync_shop_list.status', 'guanyuan_sync_shop_list.cashierSystem', 'kf_shops.shopCode', 'kf_shops.id'])
                ->get()
                ->toArray();
        } else {// 取开店相关信息
            $getShopAttributeData = CommonService::getShopAttributeData();// rms门店属性配置
            $siteSelectionGrade   = collect($getShopAttributeData)
                ->where('id', SiteLocationEnum::CATEGORY_ID_5)// 选址场景分级 单选 S A B C D
                ->first();

            return OpenShopSignOrderModel::query()
                ->leftJoin('open_shop_main_process', 'open_shop_main_process.id', '=', 'open_shop_sign_order.mainProcessId')
                ->leftJoin('open_shop_site_locations', 'open_shop_site_locations.orderNo', '=', 'open_shop_sign_order.orderNo')
                ->whereIn('open_shop_sign_order.status', [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE])
                ->whereRaw('open_shop_sign_order.id IN ( SELECT MAX( id ) FROM open_shop_sign_order where status in (1,2) GROUP BY shopCode ) ')
                ->whereIn('open_shop_main_process.shopId', $shopIds)
                ->where('open_shop_site_locations.isDeleted', 0)
                ->selectRaw(
                    'open_shop_main_process.shopId,open_shop_sign_order.orderNo,
                open_shop_site_locations.doorHeadWidth engineeringExhibitionArea,open_shop_site_locations.area engineeringArea,
                    open_shop_site_locations.depth engineeringDepth,open_shop_site_locations.electricityConsumption engineeringElectricity,
                    open_shop_site_locations.townGrade,open_shop_site_locations.mallGrade,open_shop_site_locations.siteSelectionGrade'
                )
                ->get()
                ->map(
                    function ($item) use ($siteSelectionGrade) {
                        $item->siteSelectionGradeId = 0;// 选址场景分级
                        if ($item->townGrade > 0) {
                            $townGradeText = ProgrammingEnum::PC_GRADE_MAPPING[$item->townGrade] ?? '';
                            foreach ($siteSelectionGrade['value'] as $v) {
                                if ($townGradeText == $v['name']) {
                                    $item->siteSelectionGradeId = $v['id'];
                                    break;
                                }
                            }
                        } elseif ($item->mallGrade != '' && $item->mallGrade != '未评级') {
                            $mallGrade = str_replace('级', '', $item->mallGrade);
                            foreach ($siteSelectionGrade['value'] as $v) {
                                if ($mallGrade == $v['name']) {
                                    $item->siteSelectionGradeId = $v['id'];
                                    break;
                                }
                            }
                        }
                        return $item;
                    }
                )
                ->toArray();
        }
    }

    /**
     * 通过门店code获得开店手机号
     * @param int $shopCode
     * @return array
     */
    public static function getShopMobileByShopCode(int $shopCode): array
    {
        // 获得进行中和正常的开店订单 可控
        $orderNoList = OpenShopSignOrderModel::query()
            ->whereIn('status', [SignOrderEnum::ORDER_STATUS_OK, SignOrderEnum::ORDER_STATUS_COMPLETE])
            ->where('shopCode', $shopCode)
            ->pluck('orderNo')
            ->toArray();

        // 通过开店订单获得手机号
        $mobile =  (string)OpenShopUserBaseInfoModel::query()
            ->whereIn('orderNo', $orderNoList)
            ->value('mobile');

        return [
            'mobile' => $mobile
        ];
    }

    /**
     * 根据稽核人员id查询对应门店区域
     * @param array $userIds
     * @param string $regionCode
     * @return array
     */
    public static function getShopCruiseManageArea(array $userIds, string $regionCode): array
    {
        return OpenShopOrganizationManageUserModel::query()
            ->where('type', OpenShopOrganizationManageUserModel::TYPE_CHECK_MANAGER)// 门店稽核顾问
            ->when(
                $userIds, function ($query) use ($userIds) {
                $query->whereIn('userId', $userIds);
            }
            )
            ->when(
                $regionCode, function ($query) use ($regionCode) {
                $query->whereRaw("JSON_CONTAINS(addressCodes, JSON_ARRAY('{$regionCode}'))");
            }
            )
            ->get()
            ->map(
                function ($item) {
                    return [
                        'userId'          => $item->userId,
                        'name'            => $item->name,
                        'addressCodesArr' => $item->addressCodesArr,
                    ];
                }
            )->toArray();
    }
}
